package com.nbgs.demo.component;

import com.nbgs.demo.dao.AuthMapper;
import com.nbgs.demo.model.ActiverUser;
import com.nbgs.demo.model.User;
import com.nbgs.demo.model.Worker;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Slf4j
public class ShiroRealm extends AuthorizingRealm {
    @Autowired
    private AuthMapper authMapper;
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        Worker worker= (Worker) principals.getPrimaryPrincipal();
        Set<String> role=new HashSet<>();
        Set<String> permission=new HashSet<>();
        List<ActiverUser> activerUsers=authMapper.activerUsers(worker.getWorkerName());
        for (ActiverUser activerUser:activerUsers){
            role.add(activerUser.getRoleName());
            permission.add(activerUser.getPermissionName());
        }
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.setRoles(role);
        simpleAuthorizationInfo.setStringPermissions(permission);
        return simpleAuthorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken usernamePasswordToken= (UsernamePasswordToken) token;
        String username=usernamePasswordToken.getUsername();
        List<Worker> workers=authMapper.workers(username);
        if (workers==null){
            throw new UnknownAccountException();
        }else if (workers!=null&&workers.size()==1){
            Worker worker=workers.get(0);
            System.out.println(worker.getWorkerPassword());
            return new SimpleAuthenticationInfo(worker,worker.getWorkerPassword(),getName());
        }else {
            throw new AuthenticationException("数据查询出现未知异常");
        }
    }
}
